<template>
  <div class="factory-account-info app-container">
    <p class="title mt8">基础信息</p>

    <a-form ref="formRef1" auto-label-width :model="form" :style="{ width: '90%' }">
      <a-row :gutter="200">
        <a-col :span="12">
          <a-form-item
            field="factoryName"
            label="企业名称"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.factoryName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            class="area-wrap"
            field="areaId"
            label="工厂地址"
            :rules="[{ required: true, message: '请选择' }]"
            :validate-trigger="['change']"
          >
            <div style="display: flex; width: 100%">
              <a-cascader
                v-model="form.areaId"
                :options="area"
                :field-names="{
                  value: 'id',
                  label: 'name'
                }"
                :style="{ width: '320px' }"
                placeholder="请选择"
                @change="changeArea"
              />
              <a-input v-model="form.location" placeholder="请输入详细地址" />
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="bossName"
            label="老板姓名"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.bossName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="bossMobile"
            label="老板电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.bossMobile" placeholder="请输入" />
            <p v-if="showMobileVo.isShowBoss" class="eyes-wrap" @click="changeIsShow(true, 'isShowBoss')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowBoss')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="buName"
            label="招商负责人"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.buName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="buMobile"
            label="招商负责人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.buMobile" placeholder="请输入" />
            <p v-if="showMobileVo.isShowTracker" class="eyes-wrap" @click="changeIsShow(true, 'isShowTracker')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowTracker')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            field="customerCategory"
            label="生产产品类别"
            :rules="[{ required: true, message: '请选择' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-tree-select
              dropdown-class-name="yyx-tree-select"
              disabled
              v-model="form.customerCategory"
              selectable="leaf"
              :multiple="true"
              :allow-clear="true"
              :allow-search="true"
              :data="treeData"
              :fieldNames="{
                key: 'categoryId',
                title: 'name',
                children: 'children'
              }"
              placeholder="请选择"
            >
              <template #tree-slot-title="node">
                <div style="display: flex; justify-content: space-between; width: 100%">
                  <p>{{ node.name }}</p>
                  <div v-if="node.children.length === 0">
                    <a-radio-group
                      v-model="node.radio"
                      @click.stop
                      @change="
                        val => {
                          changeRadio(val, node);
                        }
                      "
                    >
                      <a-radio value="A">自生产</a-radio>
                      <a-radio value="B">非自生产</a-radio>
                    </a-radio-group>
                  </div>
                </div>
              </template>
            </a-tree-select>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            field="orgDesc"
            label="优势备注"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-textarea v-model="form.orgDesc" placeholder="请介绍工厂优势" allow-clear />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            class="kp-edit"
            field=""
            label="是否开票与税点设置"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <div class="jzt-flex-bt" style="width: 100%">
              <div>
                <span class="label">是否开票</span>
                <a-select v-model="form.isSupportBilling" :style="{ width: '100%' }" placeholder="请选择">
                  <a-option :value="1">是</a-option>
                  <a-option :value="0">否</a-option>
                </a-select>
              </div>
              <div>
                <span class="label">专票税点</span>
                <a-input-number
                  v-model="form.specialTicket"
                  :style="{ width: '100%' }"
                  placeholder="请输入"
                  allow-clear
                  :min="0"
                  :max="100"
                  :precision="2"
                >
                  <template #suffix>%</template>
                </a-input-number>
              </div>
              <div>
                <span class="label">普通票税点</span>
                <a-input-number
                  v-model="form.ordinaryTicket"
                  :style="{ width: '100%' }"
                  placeholder="请输入"
                  allow-clear
                  :min="0"
                  :max="100"
                  :precision="2"
                >
                  <template #suffix>%</template>
                </a-input-number>
              </div>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item
            class="sk-plan"
            field=""
            label="分期收款计划"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <template #label>
              <div style="display: inline-block; text-align: right">
                <p>分期收款计划</p>
              </div>
            </template>
            <div v-if="planData.length <= 0" class="plan-table-wrap" style="width: 100%; margin-bottom: 12">
              <header></header>
              <div class="jzt-flex-center" style="height: 40px">
                <div>
                  <p>暂时没有数据</p>
                </div>
              </div>
            </div>
            <div v-else style="width: 100%; margin-bottom: 12">
              <a-table class="jzt-table" :columns="columns" :data="planData" :pagination="false">
                <template #collectionType="{ record }">
                  <p>{{ record.collectionType }}期款项</p>
                </template>
                <template #businessNode="{ record }">
                  <p>{{ getNodeName(record.businessNode) }}</p>
                </template>
                <template #collectionScale="{ record }">
                  <p>{{ record.collectionScale }}%</p>
                </template>
                <template #collectionNode="{ record }">
                  <p>{{ getNodeName(record.collectionNode) }}</p>
                </template>
                <template #collectionCycle="{ record }">
                  <p v-if="record.collectionCycle > 0">{{ record.collectionCycle }}（{{ record.collectionCycle }}个自然日）</p>
                  <p v-else>0（立即转款）</p>
                </template>
              </a-table>
              <div style="display: flex">
                <p style="color: #3d3d3d">
                  对账人姓名/电话：{{ planObj?.reconciliationName || "-" }} {{ planObj?.reconciliationMobile || "-" }}
                </p>
                <a-divider direction="vertical" />
                <p style="color: #3d3d3d">
                  开发人姓名/电话：{{ planObj?.exploitName || "-" }} {{ planObj?.exploitMobile || "-" }}
                </p>
              </div>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- ========================================================================================= -->
    <div class="line"></div>

    <p class="title mt44">完善信息</p>
    <a-form ref="formRef2" auto-label-width :model="form" :style="{ width: '90%' }">
      <a-row :gutter="200">
        <a-col :span="24">
          <a-form-item field="cooperationAgreemId" label="合作协议">
            <div style="width: 100%">
              <a-upload
                :file-list="fileList.cooperationAgreemIdFileList"
                class="area-upload"
                action="/"
                :auto-upload="false"
                :show-file-list="false"
                ref="uploadAgreeFileRef"
                @change="
                  (files, file) => {
                    handleAvatarChangeIcon('cooperationAgreemId', files, file);
                  }
                "
              >
                <template #upload-button>
                  <a-space v-if="!(form._cooperationAgreemId || form.cooperationAgreemUrl)">
                    <a-button type="text">
                      <icon-upload />
                      <p class="f12">上传文件</p>
                    </a-button>
                  </a-space>

                  <div v-else>
                    <div
                      class="pl20 pr20"
                      style="width: 100%; display: flex; justify-content: space-between; box-sizing: border-box"
                    >
                      <!-- {{ fileList.cooperationAgreemIdFileList[0]?.name }} -->
                      {{ getUrltoName(form._cooperationAgreemId || form.cooperationAgreemUrl) }}
                      <div classs="btn-wrap">
                        <a-button type="outline" class="mr14"> 重新上传 </a-button>
                        <a-button
                          type="primary"
                          @click.stop="downloadFile(form._cooperationAgreemId || form.cooperationAgreemUrl)"
                          >下载</a-button
                        >
                      </div>
                    </div>
                  </div>
                </template>
              </a-upload>
              <!-- <p>{{ form._cooperationAgreemId || form.cooperationAgreemUrl }}</p> -->
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="busFile" label="营业执照">
            <a-upload
              :file-list="fileList.businessLicenseIdFileList"
              class="area-upload card-area-upload"
              action="/"
              :auto-upload="false"
              :show-file-list="false"
              ref="uploadeBusFileRef"
              @change="
                (files, file) => {
                  handleAvatarChangeIcon('businessLicenseId', files, file, null, false, 'img');
                }
              "
            >
              <template #upload-button>
                <div class="img-wrap" v-if="form.businessLicenseId">
                  <img :src="form._businessLicenseId || form.businessLicenseUrl" />
                </div>
                <a-space v-else>
                  <a-button type="text">
                    <IconPlus />
                  </a-button>
                </a-space>
              </template>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="orgCreatDate" label="成立日期">
            <a-date-picker v-model="form.orgCreatDate" style="width: 254px" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="orgValid" label="有效期">
            <a-range-picker v-model="form.orgValid" style="width: 254px" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="workerNum" label="生产员工人数">
            <a-input-number v-model="form.workerNum" placeholder="请输入" :min="0" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="workerNum" label="工人数量">
            <a-input-number v-model="form.factoryWorkersCount" placeholder="请输入" :min="0" :step="1" :precision="0" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="outPutNum" label="年度产值时间段">
            <div class="upload-output-wrap">
              <a-range-picker v-model="form.outputVal" style="width: 254px; margin-bottom: 10px" />
              <div style="width: 100%">
                <a-upload
                  action="/"
                  class="area-upload"
                  :auto-upload="false"
                  :show-file-list="false"
                  ref="uploadOutPutNumRef"
                  @change="
                    (files, file) => {
                      handleAvatarChangeIcon('outputValId', files, file);
                    }
                  "
                >
                  <template #upload-button>
                    <a-space v-if="!(form._outputValId || form.outputValUrl)">
                      <a-button type="text">
                        <icon-upload />
                        <p class="f12">上传文件</p>
                      </a-button>
                    </a-space>

                    <div v-else>
                      <div
                        class="pl20 pr20"
                        style="width: 100%; display: flex; justify-content: space-between; box-sizing: border-box"
                      >
                        {{ getUrltoName(form._outputValId || form.outputValUrl) }}
                        <div classs="btn-wrap">
                          <a-button type="outline" class="mr14"> 重新上传 </a-button>
                          <a-button type="primary" @click.stop="downloadFile(form._outputValId || form.outputValUrl)"
                            >下载</a-button
                          >
                        </div>
                      </div>
                    </div>
                  </template>
                </a-upload>
                <!-- <p>{{ form._outputValId || form.outputValUrl }}</p> -->
              </div>
            </div>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="annualOutputValue"
            label="年度产值"
            :rules="[{ required: true, message: '请输入正确的值' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.annualOutputValue" placeholder="请输入" @input="handleInput" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="plantArea"
            label="厂房面积"
            :rules="[{ required: true, message: '请输入正确的值' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.plantArea" placeholder="请输入" @input="handleInputtwo" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="financeReconciliationName"
            label="财务对账人"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.financeReconciliationName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="financeReconciliationMobile"
            label="财务对账人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.financeReconciliationMobile" placeholder="请输入" />
            <p v-if="showMobileVo.isShowFinance" class="eyes-wrap" @click="changeIsShow(true, 'isShowFinance')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowFinance')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>

        <a-col :span="12">
          <a-form-item
            field="trackerManagerName"
            label="跟单负责人"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.trackerManagerName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="trackerManagerTel"
            label="负责人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.trackerManagerTel" placeholder="请输入" />
            <p v-if="showMobileVo.isShowManager" class="eyes-wrap" @click="changeIsShow(true, 'isShowManager')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowManager')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="trackerName"
            label="跟单人员"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.trackerName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="trackerTel"
            label="跟单人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.trackerTel" placeholder="请输入" />
            <p v-if="showMobileVo.isShowTrackerManage" class="eyes-wrap" @click="changeIsShow(true, 'isShowTrackerManage')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowTrackerManage')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="aftersaleName"
            label="售后人员"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.aftersaleName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="aftersaleTel"
            label="售后人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.aftersaleTel" placeholder="请输入" />
            <p v-if="showMobileVo.isShowAfterSaleManage" class="eyes-wrap" @click="changeIsShow(true, 'isShowAfterSaleManage')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowAfterSaleManage')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="aftersaleManageName"
            label="售后负责人"
            :rules="[{ required: true, message: '请输入' }]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.aftersaleManageName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            field="aftersaleManageTel"
            label="售后负责人电话"
            :rules="[
              { required: true, message: '请输入' },
              { match: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
            :validate-trigger="['change', 'input']"
          >
            <a-input v-model="form.aftersaleManageTel" placeholder="请输入" />
            <p v-if="showMobileVo.isShowAfterSale" class="eyes-wrap" @click="changeIsShow(true, 'isShowAfterSale')">
              <img src="@/assets/images/open-eyes.png" alt="" />显示
            </p>
            <p v-else class="eyes-wrap" @click="changeIsShow(false, 'isShowAfterSale')">
              <img src="@/assets/images/close-eyes.png" alt="" />隐藏
            </p>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item field="isQuaCheck" label="是否有质检流程">
            <a-radio-group v-model="form.isQuaCheck">
              <a-radio :value="1">有</a-radio>
              <a-radio :value="0">无</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="quaCheckDesc" label="质检流程说明">
            <a-textarea
              v-model="form.quaCheckDesc"
              placeholder="请简要说明质检流程，如“从生产到加工到成品环节中涉及质检范畴事项”"
              allow-clear
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item field="ycInfo" label="验厂资料">
            <div style="width: 100%">
              <a-upload
                :file-list="form.checkFactoryPicUrls"
                class="area-upload card-area-upload yc-upload"
                action="/"
                :auto-upload="false"
                ref="uploadycIconRef"
                list-type="picture-card"
                image-preview
                :show-upload-button="false"
                :show-retry-button="false"
                :show-preview-button="false"
                :show-remove-button="true"
                multiple
                :limit="8"
                @change="
                  (files, file) => {
                    handleAvatarChangeIcon('checkFactoryPicIds', files, file, null, true, 'img', 'checkFactoryPicUrls');
                  }
                "
              >
                <template #upload-button>
                  <a-space>
                    <a-button type="text" :disabled="form.checkFactoryPicIds.length >= 8" class="upload-btn">
                      <div>
                        <IconPlus />
                      </div>
                    </a-button>
                  </a-space>
                </template>
              </a-upload>
              <p class="f12 mt10" style="color: #86909c">量最多8张，单张不超过10M,支持jpeg，jpg，png格式;主题鲜明、图片清晰。</p>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <!-- 分期收款计划-抽屉 -->
    <PlanDrawer v-model:isOpen="isOpenPlan" />

    <!-- <a-button @click="getFormData">获取信息</a-button> -->
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { IconPlusCircleFill, IconDelete, IconUpload, IconPlus } from "@arco-design/web-vue/es/icon";
import china from "@/utils/china.json";
import { imgsUploadFac } from "@/apis";
import { Message } from "@arco-design/web-vue";
import PlanDrawer from "./planDrawer.vue";

const form = ref<any>({ brandList: [{}], checkFactoryPicIds: [] });
const formRef1 = ref();
const formRef2 = ref();
const treeData = ref<any>([]);
const uploadAgreeFileRef = ref();
const uploadeBusFileRef = ref();
const uploadOutPutNumRef = ref();
const uploadBrandIconRef = ref();
const uploadBrandRef = ref();
const area = ref(china);
const fileList = ref({
  cooperationAgreemIdFileList: [] as any,
  businessLicenseIdFileList: [] as any,
  outputValIdFileList: [] as any,
  bandPicIdFileList: [] as any,
  bandFileIdFileList: [] as any
});
const _detailInfo = ref({});
const columns = ref([
  {
    title: "收款类型",
    dataIndex: "collectionType",
    slotName: "collectionType"
  },
  {
    title: "商家付款节点",
    dataIndex: "businessNode",
    slotName: "businessNode"
  },
  {
    title: "商家付款比例",
    dataIndex: "collectionScale",
    slotName: "collectionScale"
  },
  {
    title: "供应商收款节点",
    dataIndex: "collectionNode",
    slotName: "collectionNode"
  },
  {
    title: "平台支付时效",
    dataIndex: "collectionCycle",
    slotName: "collectionCycle"
  }
]);
const planObj = ref({});
const planData = ref([]);
const isOpenPlan = ref(false);
const showMobileVo = ref({
  isShowBoss: false,
  isShowTracker: false,
  isShowManager: false,
  isShowTrackerManage: false,
  isShowAfterSaleManage: false,
  isShowAfterSale: false,
  isShowFinance: false
});

const props = defineProps({
  detailInfo: {
    type: Object,
    default: () => {}
  }
});

onMounted(() => {
  treeData.value = [];
  addNewProperty(treeData.value, "disabled");
  console.log("产品类别===", treeData.value);
});

watch(
  () => props.detailInfo,
  val => {
    if (val) {
      _detailInfo.value = JSON.parse(JSON.stringify(val));
      editReview();
    }
  },
  { deep: true }
);

const changeIsShow = (val: boolean, key: string) => {
  showMobileVo.value[key] = !val;
  if (!val) {
    // 当前key以外的所有key全部重置为false
    const keys = Object.keys(showMobileVo.value);
    keys.map(item => {
      if (item !== key) {
        showMobileVo.value[item] = false;
      }
    });
  }
};

//获取收款节点-中文
const getNodeName = (type: number) => {
  const arr = [
    { label: "接单付款", value: "1" },
    { label: "生产完成确认", value: "2" },
    { label: "已发货", value: "3" },
    { label: "入库完成", value: "4" },
    { label: "配送完成 ", value: "5" },
    { label: "安装完成", value: "6" }
  ];
  const obj = arr.find(item => item.value === type);
  return obj?.label || "--";
};
const handleInput = (value: string) => {
  // 替换非数字和小数点字符
  let numericValue = value.replace(/[^\d.]/g, "");
  // 保证只有一个小数点
  const decimalIndex = numericValue.indexOf(".");
  if (decimalIndex !== -1) {
    // 只保留第一个小数点后最多两位数字
    const integerPart = numericValue.slice(0, decimalIndex);
    const decimalPart = numericValue.slice(decimalIndex + 1).slice(0, 2); // 最多两位小数
    numericValue = `${integerPart}${decimalIndex !== -1 ? "." : ""}${decimalPart}`;
  }
  if (numericValue.length > 20) {
    numericValue = numericValue.slice(0, 20);
  }
  form.value.annualOutputValue = numericValue;
};
const handleInputtwo = (value: string) => {
  // 替换非数字和小数点字符
  let numericValue = value.replace(/[^\d.]/g, "");
  // 保证只有一个小数点
  const decimalIndex = numericValue.indexOf(".");
  if (decimalIndex !== -1) {
    // 只保留第一个小数点后最多两位数字
    const integerPart = numericValue.slice(0, decimalIndex);
    const decimalPart = numericValue.slice(decimalIndex + 1).slice(0, 2); // 最多两位小数
    numericValue = `${integerPart}${decimalIndex !== -1 ? "." : ""}${decimalPart}`;
  }
  if (numericValue.length > 20) {
    numericValue = numericValue.slice(0, 20);
  }
  form.value.plantArea = numericValue;
};
//url获取文件名称
const getUrltoName = (url: string) => {
  return decodeURIComponent(url?.split("/")[url?.split("/").length - 1]);
};

const editReview = () => {
  // 编辑的时候，数据回显
  console.log("账户信息回显1===", _detailInfo.value);
  form.value = { ..._detailInfo.value };
  form.value.orgValid = [form.value.orgValidStart, form.value.orgValidEnd];
  form.value.outputVal = [form.value.outputValStart, form.value.outputValEnd];
  form.value.specialTicket = form.value.specialTicket ? Number(form.value.specialTicket) : null;
  form.value.ordinaryTicket = form.value.ordinaryTicket ? Number(form.value.ordinaryTicket) : null;
  const _checkFactoryPicUrls = form.value.checkFactoryPicUrls?.map((item, index) => {
    return {
      url: item,
      uid: form.value.checkFactoryPicIds[index]
    };
  });
  form.value.checkFactoryPicUrls = _checkFactoryPicUrls;
  // if (_detailInfo.value?.brandList.length === 0) {
  //   form.value.brandList = [{}];
  // }
  // 合作协议回显
  if (form.value.cooperationAgreemId && form.value.cooperationAgreemUrl) {
    const urlSplit = form.value.cooperationAgreemUrl ? form.value.cooperationAgreemUrl.split("/") : [];
    fileList.value.cooperationAgreemIdFileList.push({
      url: form.value.cooperationAgreemUrl,
      uid: form.value.cooperationAgreemId,
      name: urlSplit[urlSplit.length - 1]
    });
  }
  //年度产值时间段回显
  if (form.value.outputValId && form.value.outputValUrl) {
    const urlSplit = form.value.outputValUrl ? form.value.outputValUrl.split("/") : [];
    fileList.value.outputValIdFileList.push({
      url: form.value.outputValUrl,
      uid: form.value.outputValId,
      name: urlSplit[urlSplit.length - 1]
    });
  }

  // 收款计划回显
  planObj.value = _detailInfo.value?.collectionPlan;
  planData.value = _detailInfo.value?.collectionPlan?.detailList || [];

  //隐藏展示手机号码对象 回显
  showMobileVo.value = _detailInfo.value?.showMobileVo || {
    isShowBoss: false,
    isShowTracker: false,
    isShowManager: false,
    isShowTrackerManage: false,
    isShowAfterSaleManage: false,
    isShowAfterSale: false,
    isShowFinance: false
  };
};

const changeArea = val => {
  console.log("改变工厂地址===", val);
};

const delBrandList = index => {
  if (form.value.brandList.length <= 1) {
    Message.error("至少有一条旗下品牌");
    return;
  }
  form.value.brandList.splice(index, 1);
};
const addBrandList = () => {
  form.value.brandList.push({});
};

const changeRadio = (val, node) => {
  console.log(909090, val, node);
};

const addNewProperty = (node, newPropertyName) => {
  for (let item of node) {
    item.radio = "A";
    // if (item.children.length > 0) {
    //   item[newPropertyName] = true;
    // } else {
    //   item[newPropertyName] = false;
    // }

    if (item.children) {
      addNewProperty(item.children, newPropertyName);
    }
  }
};

const getFormData = async () => {
  let accountInfo = {};

  if (
    !(
      form.value?.isSupportBilling !== "" &&
      form.value?.isSupportBilling !== null &&
      form.value?.isSupportBilling !== undefined &&
      form.value?.specialTicket !== "" &&
      form.value?.specialTicket !== null &&
      form.value?.specialTicket !== undefined &&
      form.value?.ordinaryTicket !== "" &&
      form.value?.ordinaryTicket !== null &&
      form.value?.ordinaryTicket !== undefined
    )
  ) {
    Message.error("请完善：是否开票、专票税点、普通票税点");
    return { accountInfo, planData: planData.value };
  }

  await Promise.all([formRef1.value.validate(), formRef2.value.validate()]).then(res => {
    console.log("校验表单信息====", res);
    if (!res[0] && !res[1]) {
      // 表单校验通过;
      accountInfo = {
        // ...form.value
        factoryName: form.value?.factoryName, //工厂名称
        areaId: form.value?.areaId, //工厂区域id
        location: form.value?.location, //详情地址
        bossName: form.value?.bossName, //老板姓名
        bossMobile: form.value.bossMobile, //老板电话
        buName: form.value?.buName, //招商负责人姓名
        buMobile: form.value?.buMobile, //招商负责人电话
        customerCategory: form.value?.customerCategory, //产品类别
        orgDesc: form.value?.orgDesc, //优势备注
        isSupportBilling: form.value?.isSupportBilling, //是否开票
        specialTicket: form.value?.specialTicket, //专票税点
        ordinaryTicket: form.value?.ordinaryTicket, //普通票税点
        orgCreatDate: form.value?.orgCreatDate, //工厂成立时间
        orgValidStart: form.value?.orgValid ? form.value?.orgValid[0] : null, //营业执照开始日期
        orgValidEnd: form.value?.orgValid ? form.value?.orgValid[1] : null, //营业执照结束日期
        cooperationAgreemId: form.value?.cooperationAgreemId, //合作附件Id
        cooperationAgreemUrl: form.value?._cooperationAgreemId, //合作附件url
        businessLicenseId: form.value?.businessLicenseId, //营业执照url
        businessLicenseUrl: form.value?._businessLicenseId, //营业执照url
        workerNum: form.value?.workerNum, //员工数量
        outputValId: form.value?.outputValId, //年度产值时间段id
        outputValUrl: form.value?._outputValId, //年度产值时间段url
        outputValStart: form.value?.outputVal ? form.value?.outputVal[0] : null, //年度产值时间段开始时间
        outputValEnd: form.value?.outputVal ? form.value?.outputVal[1] : null, //年度产值时间段结束时间
        // brandList: form.value?.brandList.map((item: any) => {
        //   return {
        //     ...item,
        //     bandName: item.bandName,
        //     bandFileId: item.bandFileId,
        //     bandFileUrl: item._bandFileId || item.bandFileUrl,
        //     bandPicId: item.bandPicId,
        //     bandPicUrl: item._bandPicId || item.bandPicUrl
        //   };
        // }), //旗下品牌数据
        factoryWorkersCount: form.value?.factoryWorkersCount, //工人数量
        annualOutputValue: form.value?.annualOutputValue, //年度产值
        plantArea: form.value?.plantArea, //厂房面积
        financeReconciliationName: form.value?.financeReconciliationName, //财务负责人
        financeReconciliationMobile: form.value?.financeReconciliationMobile, //财务负责人电话
        trackerManagerName: form.value?.trackerManagerName, //跟单负责人
        trackerManagerTel: form.value?.trackerManagerTel, //跟单负责人电话
        trackerName: form.value?.trackerName, //跟单员
        trackerTel: form.value?.trackerTel, //跟单员电话
        aftersaleName: form.value?.trackerTel, //售后人员
        aftersaleTel: form.value?.aftersaleTel, //售后人员电话
        aftersaleManageName: form.value?.aftersaleManageName, //售后负责人
        aftersaleManageTel: form.value?.aftersaleManageTel, //售后负责人电话
        isQuaCheck: Number(form.value?.isQuaCheck), //是否有质检流程
        quaCheckDesc: form.value?.quaCheckDesc, //质检流程说明
        checkFactoryPicIds: form.value?.checkFactoryPicIds, //验厂资料id
        checkFactoryPicUrls: form.value?._checkFactoryPicIds, //验厂资料url
        showMobileVo: showMobileVo.value //隐藏展示手机号码对象
      };
      console.log("账户信息====", form.value, accountInfo);
    }
  });
  return { accountInfo: accountInfo, planData: planData.value };
};

defineExpose({
  getFormData
});

//====================================文件上传========================================================================================

import useMultipartOssStore from "@/stores/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import { getFolder, _debounce } from "@/utils/index";

const handleAvatarChangeIcon = _debounce(
  async (key: string, files: any, file: any, item?: any, multiple = false, type = "all", speKey?: string) => {
    //选中文件触发的change事件
    let doneFiles = [];
    if (!multiple) {
      // 不是多选，清空文件列表
      fileList.value[key + "FileList"] = [];
      console.log("1111111111清空", key + "FileList");
    } else {
      // 多选，清空form里面存的对应值[]
      form.value[key] = [];
      form.value["_" + key] = [];
      const doneFiles = files.filter(item => item.status === "done");
      console.log("已经存在的图片===", doneFiles);
      for (let item of doneFiles) {
        form.value[key].push(item.uid);
        form.value["_" + key].push(item.url);
      }
    }
    let _files = files.filter(item => item.status !== "done");
    //文件格式校验
    const flag = fileType(type, _files);
    if (!flag) {
      let normalFiles = [];
      if (type === "img") {
        Message.error("只能上传图片文件");
        normalFiles = _files.filter(item => {
          if ((item.file && (item.file.type === "image/jpeg" || item.file.type === "image/png")) || !item.file) {
            return item;
          }
        });
        if (speKey) {
          form.value[speKey] = [...doneFiles, ...normalFiles];
        }
      }
      if (normalFiles.length <= 0) {
        return;
      } else {
        _files = normalFiles;
      }
    }
    for (let obj of _files) {
      await customUpload({ file: obj }, item, key, multiple);
    }
  },
  100
);
/**
 * 校验文件类型
 */
const fileType = (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.file.type === "image/jpeg" || item.file.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  }
  return flag;
};
/**
 * 上传
 */
const customUpload = async (option, item, key, multiple) => {
  const folder = getFolder();
  const objName = folder + option.file.name;
  await ossStore
    .submit(objName, option.file.file)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      console.log("文件上传成功，地址为===", res.fileUrl.split("?")[0]);
      const temp = String(new Date().getTime());
      const num = String(Math.floor(Math.random() * (99 - 10 + 1)) + 10);
      const uid = Number(temp + num);
      if (item) {
        item[key] = uid;

        item["_" + key] = res.fileUrl.split("?")[0];
      } else {
        if (multiple) {
          form.value[key].push(uid);
          form.value["_" + key].push(res.fileUrl.split("?")[0]);
        } else {
          form.value[key] = uid;
          form.value["_" + key] = res.fileUrl.split("?")[0];
        }
      }
      uploadIMG(option, objName, res.fileUrl.split("?")[0], uid); //图片上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
//将图片上传到业务端服务
const uploadIMG = (option, objName, url, uid) => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: uid,
      objectName: objName, //目录＋文件名称
      url: url,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUploadFac(uploadArr);
};
/**
 * 下载附件
 */
const downloadFile = url => {
  console.log("这是下载附件操作", url);
  const urlSplit = url ? url.split("/") : [];
  const name = decodeURIComponent(urlSplit[urlSplit.length - 1]);
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (xhr.status === 200) {
      let file = xhr.response;
      let fileName = name;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(file, fileName);
      } else {
        let fileUrl = window.URL.createObjectURL(file);
        let a = document.createElement("a");
        a.download = fileName;
        a.href = fileUrl;
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
      }
    }
  };
  xhr.send();
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>
<style lang="scss">
.eyes-wrap {
  width: 88px;
  text-align: right;
  cursor: pointer;
  img {
    vertical-align: middle;
    margin-right: 8px;
  }
}
.factory-account-info {
  .arco-select-view-multiple.arco-select-view-size-medium,
  .arco-textarea,
  .arco-picker {
    background-color: #f2f3f5;
  }

  .arco-select-view-single {
    background-color: #f2f3f5;
  }
}

.factory-account-info {
  .arco-select-view.arco-select-view-size-medium.arco-select-view-has-tag.arco-select-view-has-suffix.arco-select-view-multiple {
    background-color: white;
  }

  .arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag {
    color: #121314;
    background-color: white;
  }

  .arco-select-view-single,
  .arco-textarea {
    background-color: #f2f3f5;
  }
}

.yyx-tree-select {
  .arco-tree-node-title-text {
    width: 100%;
  }
}
</style>
<style lang="scss" scoped>
:deep(.area-wrap) {
  .arco-select-view-single {
    border-radius: 2px 0px 0px 2px !important;
    border-right: 1px solid #dcdfe6 !important;
  }
  .arco-input-wrapper {
    border-radius: 0px 2px 2px 0px !important;
  }
}
:deep(.arco-row.kp-edit) {
  align-items: center;
}
.factory-account-info.app-container {
  height: calc(100vh - 384px);
  overflow-y: auto;
}

:deep(
    .factory-account-info
      .arco-select-view.arco-select-view-size-medium.arco-select-view-has-tag.arco-select-view-has-suffix.arco-select-view-multiple
  ) {
  background-color: red;
}

:deep(.arco-tree-node-title-text) {
  width: 100%;
}

:deep(.area-upload.arco-upload) {
  span {
    display: inline-block;
    width: 100%;
    line-height: 32px;
  }
}

:deep(.arco-btn.upload-btn) {
  width: 80px;
  height: 80px;
}

p.title {
  font-size: 18px;
  color: #131414;
  margin-bottom: 24px;
}

.brand-wrap {
  width: 100%;

  & > div {
    display: flex;
  }

  .brand-icon-wrap {
    display: flex;

    & > div {
      width: 200px;
      margin-right: 50px;

      & > p {
        word-wrap: break-word;
      }
    }

    .arco-upload-wrapper.arco-upload-wrapper-type-text.area-upload.card-area-upload {
      width: 100px;
      height: 100px;

      .arco-upload {
        height: 100%;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.upload-output-wrap {
  width: 100%;

  & > span {
    margin-bottom: 4px;
  }
}

.yc-upload {
  width: 100%;

  .arco-upload {
    width: 100px;
    height: 100px;
    display: flex !important;
    align-items: center;
    justify-content: center;
  }

  .arco-upload-list-picture {
    width: 100px;
    height: 100px;
  }

  .arco-upload-list.arco-upload-list-type-picture-card {
    width: 100%;

    .arco-upload.arco-upload-type-picture-card.arco-upload-hide {
      width: 100px;
    }
  }
}

.arco-tree-node-title-text {
  width: 100% !important;
}
</style>
<style lang="scss" scoped>
:deep(.sk-plan) {
  .arco-form-item-label {
    display: flex;
    .arco-btn {
      margin-right: -15px;
    }
    .arco-form-item-label-required-symbol {
      margin-top: 10px;
    }
  }
}
:deep(.jzt-table.arco-table) {
  margin-bottom: 10px;
  thead {
    .arco-table-th {
      background-color: #f2f6fc;
      color: #3d3d3d;
      .arco-table-th-title {
        font-weight: normal;
        font-size: 16px;
      }
    }
  }
  tbody {
    .arco-table-tr {
      .arco-table-td-content {
        color: #606266;
      }
    }
  }
}
.jzt-flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.plan-table-wrap {
  border: 1px solid #dcdfe6;
  header {
    width: 100%;
    height: 50px;
    background-color: #f2f6fc;
  }
  .jzt-flex-center {
    padding: 20px 0 20px 0;
    & > div {
      text-align: center;
      p {
        color: #86909c;
        margin-bottom: 12px;
      }
    }
  }
}
.jzt-flex-bt {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 100px;
  border: 1px solid #dcdfe6;
  padding: 16px 20px;
  & > div {
    display: grid;
    grid-template-columns: 80px 1fr;
  }
  .label {
    display: inline-block;
    text-align: right;
    padding-right: 10px;
    line-height: 32px;
  }
}
.line {
  height: 20px;
  margin: 0 -20px;
  background-color: #f5f7fa;
}

.area-upload {
  &.arco-upload {
    box-sizing: border-box;
    width: 100%;
    background-color: #f2f3f5;
    display: flex;
    align-items: center;
    height: 64px;
  }

  :deep(.arco-upload) {
    display: inline-block;
    box-sizing: border-box;
    background-color: #f2f3f5;
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  :deep(.arco-upload-list) {
    .arco-upload-list-item {
      margin-top: 2px;
    }

    .arco-upload-list-item-operation,
    .arco-upload-progress {
      display: none;
    }
  }
}

:deep(.card-area-upload) {
  &.arco-upload.area-upload {
    display: inline-block;
    box-sizing: border-box;
    background-color: #f2f3f5;
    width: 200px;
    height: 120px;

    & > span {
      display: inline-block;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      .img-wrap {
        width: 100%;
        height: 100%;
      }

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }
}
</style>
